package com.qf.sl.youshare.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.qf.sl.youshare.Constants;
import com.qf.sl.youshare.activity.CoreGoodsActivity;
import com.qf.sl.youshare.R;
import com.qf.sl.youshare.adapters.StoreCoreAdapter;
import com.qf.sl.youshare.model.Product;
import com.qf.sl.youshare.tasks.ProductListTask;
import com.qf.sl.youshare.tasks.TaskProcessor;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by IDEA
 * User : sl
 * on 2015/2/5.
 * 16:19
 */
public class StoreCoreFragment
        extends Fragment
        implements TaskProcessor, AdapterView.OnItemClickListener {

    /**
     * 用于标记是否已经加载过一次数据
     */
    private boolean hasFirstLoad = false;
    private LinkedList<Product> products;
    private StoreCoreAdapter adapter;

    public StoreCoreFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_store_core, container, false);

        ListView listView = (ListView) ret.findViewById(R.id.store_core_product_list);

        if (listView != null) {
            //TODO 设置Adapter
            products = new LinkedList<Product>();
            adapter = new StoreCoreAdapter(getActivity(), products);

            listView.setAdapter(adapter);

            listView.setOnItemClickListener(this);

        }

        if (!hasFirstLoad){
            ProductListTask task = new ProductListTask(this);
            //参数;       id, size
            task.execute("1","10");
        }

        return ret;
    }

    /**
     * 异步任务更新UI的回调方法
     * @param jsonObject 获取的json数据
     */
    @Override
    public void processResult(JSONObject jsonObject) {
        //TODO 显示商品的列表

        if (jsonObject != null) {
//            System.out.println("jsonObject = " + jsonObject);

            try {
                int code = jsonObject.getInt("code");
                if (code == 1){
                    //TODO 正确数据,需要解析
                    JSONObject msg = jsonObject.getJSONObject("msg");
                    JSONObject data = msg.getJSONObject("data");
                    Iterator keys = data.keys();

                    List<Product> productList = new LinkedList<Product>();

                    while (keys.hasNext()){
                        Object key = keys.next();
                        JSONObject object = data.getJSONObject((String) key);

                        Product product = new Product();//高内聚
                        product.parseJSON(object);
                        productList.add(product);
                    }

                    //注意: 如果是刷新数据,那么products成员变量就要清空,然后
                    //          用productList里面的内容添加到 products 中,
                    //          相当于ListView重新加载
                    //     如果需要实现"加载更多"的操作,那么就不能够清空 list, 而是直接添加

                    products.addAll(productList);
                    adapter.notifyDataSetChanged();


                }else {
                    String msg = jsonObject.getString("msg");
                    System.out.println("msg = " + msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            hasFirstLoad = true;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Product product = products.get(position);
        Intent intent = new Intent(getActivity(), CoreGoodsActivity.class);

        int upColor = Constants.COLORS[position % Constants.COLORS.length];
        int downColor = 0xFFFFFFFF;

        String goodsId = product.getGoodsId();
        String name = product.getName();
        String goodsBrief = product.getGoodsBrief();
        String goodsThumb = product.getGoodsThumb();
        String price = product.getPromotePrice();
        String type = product.getType();

        if (price.equals("") || !(price.length() > 0)){
            price = product.getShopPrice();
            if (price.equals("") || !(price.length() > 0)){
                price = product.getMarketPrice();
            }
        }

        intent.putExtra("goodsId",goodsId);
        intent.putExtra("upColor", upColor);
        intent.putExtra("downColor", downColor);
        intent.putExtra("name", name);
        intent.putExtra("goodsBrief", goodsBrief);
        intent.putExtra("goodsThumb", goodsThumb);
        intent.putExtra("price", price);
        intent.putExtra("type", type);

        startActivity(intent);
    }
}